package com.yonyou.lexue.lexuemgr.web.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.json.JSONException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.utils.Clock;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.lexue.lexuemgr.entity.Comment;
import com.yonyou.lexue.lexuemgr.entity.DTO;
import com.yonyou.lexue.lexuemgr.entity.Note;
import com.yonyou.lexue.lexuemgr.entity.User;
import com.yonyou.lexue.lexuemgr.service.account.AccountService;
import com.yonyou.lexue.lexuemgr.service.comment.CommentService;
import com.yonyou.lexue.lexuemgr.service.note.NoteService;
import com.yonyou.lexue.lexuemgr.service.task.TaskService;
import com.yonyou.lexue.lexuemgr.utils.DateUtils;
import com.yonyou.lexue.lexuemgr.utils.FormatDateUtils;


@Controller
@RequestMapping("app")
@SuppressWarnings("rawtypes")
public class AppController {
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private NoteService noteService;
	
	@Autowired
	private CommentService commentService;
	
	private Clock clock = Clock.DEFAULT;
	
	@ResponseBody
	@RequestMapping(value = "testAppHttp",method=RequestMethod.POST,produces = "application/json; charset=utf-8")
	public String textAppHttp(HttpServletRequest request){
		
		System.out.println(request.getParameter("text"));
//		System.out.println(request.getParameter("data"));
		JSONObject json=new JSONObject();
		json.put("text","111");
		return json.toString();
	}
	
	/**
	 * 新增笔记
	 */
	@ResponseBody
	@RequestMapping(value = "addNote",method=RequestMethod.POST,produces = "application/json; charset=utf-8")
	public JSONObject saveNoteByApp(HttpServletRequest request){
		JSONObject retJson=new JSONObject();
		String userId=request.getParameter("userId");
		String courseId=request.getParameter("courseId");
		String noteContent=request.getParameter("noteContent");
		if(userId==null||userId.equals("")){
			retJson.put("msg", "新增失败,用户为空！ ");
        	retJson.put("status",false);
        	return retJson;
		}
		if(courseId==null||courseId.equals("")){
			retJson.put("msg", "新增失败,课程为空！ ");
        	retJson.put("status",false);
        	return retJson;
		}
//		String reqJson=request.getParameter("userId");
		Note note = new Note();
		note.setUserId(userId);
		note.setCourseId(courseId);
		note.setNoteContent(noteContent);
		note.setCreateDate(clock.getCurrentDate());
		try {
			noteService.saveNote(note);
			retJson.put("msg", "新增成功");
        	retJson.put("status",true);
		} catch (Exception e) {
			retJson.put("msg", "新增失败 "+e.getMessage());
        	retJson.put("status",false);
        	return retJson;
		}
		
		return retJson;
	}
	
	/**
	 * 返回笔记记录
	 * @throws JSONException 
	 */
	@ResponseBody
	@RequestMapping(value = "getNoteInfo",method=RequestMethod.POST)
	public JSONObject getNoteContent(HttpServletRequest request,HttpServletResponse response){
		String userId=request.getParameter("userId");
		String courseId=request.getParameter("courseId");
		JSONObject json=new JSONObject();
		JSONObject retJson=new JSONObject();
		JSONArray jsonArray = new JSONArray();
		List<Note> noteList = null;
        try {
        	noteList = noteService.getNotes(userId, courseId);
        	if(noteList.size()<=0){
        		retJson.put("msg", "暂无记录");
            	retJson.put("data", "");
            	retJson.put("status",false);
            	return retJson;
        	}
        	Date createDate = null;
        	String fromToday = null;
        	for (Note note : noteList) {
        		createDate = note.getCreateDate();
        		fromToday = FormatDateUtils.fromToday(createDate);
        		json = JSONObject.fromObject(note);
        		json.put("fromToday", fromToday);
        		jsonArray.add(json);
			}
        	retJson.put("msg", "请求成功");
        	retJson.put("data", jsonArray);
        	retJson.put("status",true);
        } catch (Exception e) {
            e.printStackTrace();
            retJson.put("msg", "请求失败! "+e.getMessage());
        	retJson.put("data", "");
        	retJson.put("status",false);
        	return retJson;
        }
        //设置可以Ajax跨域访问
  		response.setHeader("Access-Control-Allow-Origin", "*");
        return retJson;
	}
	
	/**
	 * 新增评价
	 */
	@ResponseBody
	@RequestMapping(value = "addComment",method=RequestMethod.POST,produces = "application/json; charset=utf-8")
	public JSONObject saveCommentByApp(HttpServletRequest request){
		JSONObject retJson=new JSONObject();
		String userId=request.getParameter("userId");
		String courseId=request.getParameter("courseId");
		String commentContent=request.getParameter("commentContent");
		String starNumber=request.getParameter("starNumber");
		if(userId==null||userId.equals("")){
			retJson.put("msg", "新增失败,用户为空！ ");
        	retJson.put("status",false);
        	return retJson;
		}
		if(courseId==null||courseId.equals("")){
			retJson.put("msg", "新增失败,课程为空！ ");
        	retJson.put("status",false);
        	return retJson;
		}
		Comment entity = new Comment();
		entity.setUserId(userId);
		entity.setCommentFlag(0);
		entity.setCourseId(courseId);
		entity.setCommentContent(commentContent);
		entity.setStarNumber(Integer.valueOf(starNumber));
		entity.setCreateDate(clock.getCurrentDate());
		try {
			List<Comment> userComments = commentService.getUserComments(userId, courseId);
			if(userComments.size()>0){
				for (Comment comment : userComments) {
					comment.setCommentFlag(1);
				}
				entity.setCommentFlag(1);
			}
			commentService.saveComment(entity);
			retJson.put("msg", "新增成功");
        	retJson.put("status",true);
		} catch (Exception e) {
			retJson.put("msg", "新增失败 "+e.getMessage());
        	retJson.put("status",false);
        	return retJson;
		}
		
		return retJson;
	}
	
	/**
	 * 返回评价记录
	 * @throws JSONException 
	 */
	@ResponseBody
	@RequestMapping(value = "getCommentInfo",method=RequestMethod.POST,produces = "application/json; charset=utf-8")
	public JSONObject getCommentContent(HttpServletRequest request){
		Integer pageNumber=Integer.valueOf(request.getParameter("pageNumber"));
		Integer pageSize=Integer.valueOf(request.getParameter("pageSize"));
		String courseId=request.getParameter("courseId");
		JSONObject json=new JSONObject();
		JSONObject retJson=new JSONObject();
		JSONArray jsonArray = new JSONArray();
		List<Comment> commentList = null;
		try {
			commentList = commentService.getComments(pageNumber, pageSize, courseId);
			if(commentList.size()<=0){
				retJson.put("msg", "暂无记录");
				retJson.put("data", "");
				retJson.put("status",false);
				return retJson;
			}
			String createDate = null;
			for (Comment comment : commentList) {
				json = JSONObject.fromObject(comment);
				createDate=DateUtils.formatDate(comment.getCreateDate(), "yyyy-MM-dd");
				json.put("createDate", createDate);
				jsonArray.add(json);
			}
			retJson.put("msg", "请求成功");
			retJson.put("data", jsonArray);
			retJson.put("status",true);
		} catch (Exception e) {
			e.printStackTrace();
			retJson.put("msg", "请求失败! "+e.getMessage());
			retJson.put("data", "");
			retJson.put("status",false);
			return retJson;
		}
		return retJson;
	}
	
	/**
	 * 展示所有人的信息/某一段时间内的信息 ,投票结果
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(method=RequestMethod.GET,value="list")
	public DTO list(@RequestParam(value="startTime",required=false) Date startTime,@RequestParam(value="endTime",required=false) Date endTime,HttpServletResponse response){
		DTO<List> dto=new DTO<List>();
		try {
//			List<User> users = null;
//			//如果开始为null的时候  那么就默认所有的数据
//			users=taskService.findAllUsers(startTime, endTime);
//			if(users==null){
//				users=new ArrayList<User>();
//			}
//			dto.setData(screen(users));
//			dto.setCode("0");
		} catch (Exception e) {
			dto.setCode("500");
			dto.setMsg("服务器出错."+e.getMessage());
			dto.setData(new ArrayList<User>());
			e.printStackTrace();
		}
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		return dto;
	}
	/**
	 * 进行投票
	 * 
	 * @param recorderId  投票人id
	 * @param reveiverId  被投票人id
	 * @param level       砖石等级
	 * @param descMsg     描述信息
	 * @return
	 */
	
	@ResponseBody
	@RequestMapping(value="vote",method=RequestMethod.POST)
	public DTO vote(@RequestParam("recorderId") Long recorderId,@RequestParam("reveiverId") Long reveiverId,@RequestParam("level") int level,@RequestParam("descMsg") String descMsg,HttpServletResponse response){
		DTO dto=new DTO();
		try {
			
//			//执行5次就加一颗钻石
//			taskService.voteStrategy(recorderId);
//			
//			Vote v=new Vote();
//			v.setReveiverId(reveiverId);
//			v.setRecorderId(recorderId);
//			v.setLevel(level);
//			v.setCreateDate(new Date());
//			v.setDescMsg(descMsg);
//			//保存投票信息
//			taskService.save(v);
//			
//			//查找被投票人的token 发送推送
//			String tt = taskService.findTokenByUserId(reveiverId);
//			job.doSendUnicast(tt, "有人给你投票啦!!!");
//			dto.setCode("0");
		} catch (Exception e) {
			dto.setCode("500");
			dto.setMsg("服务器出现错误"+e.getMessage());
			e.printStackTrace();
		}
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		return dto;
	}
	
	
	
}
